import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
  BetaSchemaForm,
  FooterToolbar,
  PageContainer,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Form, Popconfirm, message } from 'antd';
import React, { useRef, useState } from 'react';
import type { TableListItem } from './data';
import { addJob, batchDel, getPlanJobPage, updateJob } from './service';
import { getStressCasePage } from '@/pages/stress-test/case/service';
import { useModel } from '@umijs/max';

const handleAdd = async (fields: any) => {
  const hide = message.loading('正在添加');

  try {
    const res = await addJob({ ...fields });
    hide();
    if (res.code == 0) {
      message.success('添加成功');
      return true;
    }
    return false
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

const handleUpdate = async (fields: any) => {
  const hide = message.loading('正在保存');

  try {
    const res = await updateJob({
      ...fields,
    });
    hide();
    if (res.code == 0) {
      message.success('保存成功');
      return true;
    }
    return false;
  } catch (error) {
    hide();
    message.error('保存失败请重试！');
    return false;
  }
};

const handleRemove = async (idList: any[], projectId: number) => {
  const hide = message.loading('正在删除');
  if (!idList) return true;

  try {
    const res = await batchDel({
      idList,
      projectId
    });
    hide();
    if (res.code == 0) {
      message.success('删除成功，即将刷新');
      return true;
    }
    return false
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList: React.FC = () => {
  const [addForm] = Form.useForm()
  const [editForm] = Form.useForm()
  const actionRef = useRef<ActionType>();
  const [selectedRowsState, setSelectedRows] = useState<any[]>([]);
  const { initialState } = useModel('@@initialState')

  const columns: ProColumns<any>[] = [
    {
      title: '任务名称',
      dataIndex: 'name',
      fixed: 'left',
      ellipsis: true,
      render(dom, entity, index, action, schema) {
        return <div>{dom}</div>
      },
    },
    {
      title: '所属用例',
      dataIndex: 'caseId',
      valueType: 'select',
      async request() {
        const res = await getStressCasePage({
          current: 1,
          pageSize: 1000,
          projectId: initialState?.currentProject?.id,
        })
        const data = res?.data?.currentData || []
        return data?.map((item: any) => ({
          label: item.name,
          value: item.id
        }))
      },
    },
    {
      title: '用例类型',
      dataIndex: 'testType',
      valueType: 'select',
      valueEnum: {
        STRESS: { text: '压测' },
        API: { text: '接口' },
        UI: { text: 'UI自动化' },
      }
    },
    {
      title: '状态',
      dataIndex: 'isDisabled',
      valueType: 'select',
      hideInForm: true,
      valueEnum: {
        1: { text: '禁用', status: 'Default' },
        0: { text: '启用', status: 'Success' },
      }
    },

    {
      title: '执行时间',
      dataIndex: 'executeTime',
      valueType: 'dateTime'
    },
    {
      title: '是否禁用',
      dataIndex: 'isDisabled',
      valueType: 'switch',
      hideInTable: true,
      hideInSearch: true,
      fieldProps: {
        checkedChildren: '禁用',
        unCheckedChildren: '启用'
      }
    },
    {
      title: '创建时间',
      dataIndex: 'gmtCreate',
      valueType: 'dateTime',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '修改时间',
      dataIndex: 'gmtModified',
      valueType: 'dateTime',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      render: (_, record) => [
        <BetaSchemaForm<any>
          key="edit"
          form={editForm}
          trigger={<a
            onClick={() => {
              editForm.setFieldsValue({
                ...record,
                isDisabled: !!record?.isDisabled
              })
            }}
          >
            编辑
          </a>}
          modalProps={{
            width: 600
          }}
          layoutType={'ModalForm'}
          // rowProps={{
          //   gutter: [16, 16],
          // }}
          // colProps={{
          //   span: 12,
          // }}
          // grid
          onFinish={async (values) => {
            const res = await handleUpdate({
              ...record,
              ...values,
              projectId: initialState?.currentProject?.id,
              isDisabled: values?.isDisabled ? 1 : 0
            })
            if (res) {
              actionRef.current?.reload()
            }
            return res
          }}
          columns={columns as any}
        />,
        <Popconfirm key='enabled' title={`是否要${record?.isDisabled ? '启用' : '禁用'}该任务？`} onConfirm={async () => {
          const res = await handleUpdate({
            id: record?.id,
            isDisabled: record?.isDisabled ? 0 : 1
          });
          if (res) {
            actionRef.current?.reload()
            setSelectedRows([]);
          }
        }}>
          <a>
            {record?.isDisabled ? '启用' : '禁用'}
          </a>
        </Popconfirm>,
        <Popconfirm key='del' title={`是否要删除该任务？`} onConfirm={async () => {
          const res = await handleRemove([record?.id], initialState?.currentProject?.id);
          if (res) {
            actionRef.current?.reload()
            setSelectedRows([]);
          }
        }}>
          <a>
            删除
          </a>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="id"
        search={{
        }}
        scroll={{ x: 'max-content' }}
        toolBarRender={() => [
          <BetaSchemaForm<any>
            key="primary"
            form={addForm}
            trigger={<Button
              type="primary"
              onClick={() => {
                addForm.resetFields()
              }}
            >
              <PlusOutlined /> 新建定时计划
            </Button>}
            modalProps={{
              width: 600
            }}
            layoutType={'ModalForm'}
            // rowProps={{
            //   gutter: [16, 16],
            // }}
            // colProps={{
            //   span: 12,
            // }}
            // grid
            onFinish={async (values) => {
              const res = await handleAdd({
                ...values,
                projectId: initialState?.currentProject?.id,
                isDisabled: values?.isDisabled ? 1 : 0
              })
              if (res) {
                actionRef.current?.reload()
              }
              return res
            }}
            columns={columns as any}
          />,
        ]}
        request={async ({ pageSize, current, ...params }) => {
          const res = await getPlanJobPage({
            projectId: initialState?.currentProject?.id,
            current,
            pageSize,
            ...params,
            isDisabled: params?.isDisabled ? 1 : (typeof params?.isDisabled == 'boolean' ? 0 : undefined)
          })

          return {
            data: res.data?.currentData || [],
            total: res.data?.totalRecords
          }
        }}
        columns={columns}
        rowSelection={{
          selectedRowKeys: selectedRowsState?.map(item => item.id),
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
              <span>
                服务调用次数总计 {selectedRowsState.reduce((pre, item) => pre + item.callNo!, 0)} 万
              </span>
            </div>
          }
        >
          <Popconfirm key='del' title={`是否要批量删除 ${selectedRowsState.length} 条？`} onConfirm={async () => {
            const res = await handleRemove(selectedRowsState?.map((item: any) => item.id), initialState?.currentProject?.id);
            if (res) {
              actionRef.current?.reload()
              setSelectedRows([]);
            }
          }}>
            <Button danger>
              批量删除
            </Button>
          </Popconfirm>
        </FooterToolbar>
      )}

    </PageContainer>
  );
};

export default TableList;
